import os
import shutil
import time

import pandas as pd

import config
from pdf_to_jpg_progrocessor import PDFToJPGProcessor


def clear_directory(directory_path):
    # 检查路径是否存在
    if os.path.exists(directory_path):
        # 遍历文件夹中的所有文件和子文件夹
        for filename in os.listdir(directory_path):
            file_path = os.path.join(directory_path, filename)
            try:
                # 如果是文件，删除文件
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                    # 如果是文件夹，递归删除文件夹及其内容
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f'Failed to delete {file_path}. Reason: {e}')
    else:
        print(f'Directory {directory_path} does not exist.')


# 检查表格中有没有表头，没有就加上
def add_header_to_excel(file_path):
    # 尝试读取Excel文件
    try:
        # 读取Excel文件
        df = pd.read_excel(file_path, header=None)

        # 检查第一行是否有数据，如果没有，则认为是没有表头
        if df.iloc[0].isnull().all():
            # 添加表头
            df.loc[-1] = ['zl', 'bdcdyh']  # 在最后添加一行
            df.index = df.index + 1  # 更新索引
            df.to_excel(file_path, index=False)  # 将修改后的DataFrame保存回Excel文件
            print(f"表头已添加到文件: {file_path}")
        else:
            print(f"文件已包含表头: {file_path}")
    except Exception as e:
        print(f"读取文件时出错: {e}")

    # 使用你的Excel文件路径替换下面的'your_excel_file.xlsx'


def main():
    start_time = time.time()  # 记录开始时间

    data_path = r'E:\workspace\house_ocr_documents'
    output_dir = data_path + r'/pics'

    config.log_file_path = data_path + r'/file.log'

    # 确保日志文件目录存在
    os.makedirs(os.path.dirname(config.log_file_path), exist_ok=True)

    # 清空或创建日志文件
    with open(config.log_file_path, 'w') as log_file:
        log_file.write("Log started for the current session.\n")

    # 清空目录
    clear_directory(data_path + r'/pics')

    table_path = ""

    # 遍历文件夹中的所有excel文件#########################################################################################
    for filename in os.listdir(data_path):
        if filename.endswith('.xlsx') or filename.endswith('.xls'):
            # 处理Excel文件的代码
            table_path = os.path.join(data_path, filename)

            logging_info = f"Processing Excel file: {table_path}"
            config.print_console_and_write_log(logging_info)
            break

    add_header_to_excel(table_path)

    # 遍历PDF文件夹中的所有PDF文件，并拆分为jpg文件###########################################################################
    for filename in os.listdir(data_path):
        if filename.lower().endswith('.pdf'):
            pdf_path = os.path.join(data_path, filename)

            processor = PDFToJPGProcessor(pdf_path, table_path)

            logging_info = f"Processing PDF file: {pdf_path}"
            config.print_console_and_write_log(logging_info)

            processor.process(output_dir)

    ####################################################################################################################

    end_time = time.time()  # 记录结束时间
    elapsed_time = end_time - start_time  # 计算总耗时（秒）

    # 将时间转换为天、小时、分钟和秒
    days = int(elapsed_time // (24 * 60 * 60))
    hours = int((elapsed_time % (24 * 60 * 60)) // (60 * 60))
    minutes = int((elapsed_time % (60 * 60)) // 60)
    seconds = int(elapsed_time % 60)

    # 输出到控制台和日志文件
    logging_info = f"Total time taken: {days} days {hours} hours {minutes} minutes {seconds} seconds"
    config.print_console_and_write_log(logging_info)


if __name__ == '__main__':
    main()
